import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {setUsername} from "@/utils/auth";
import { constantRoutes } from '@/router'
import Layout from '@/layout/index'
import SubDirMenu from '@/layout/SubDirMenu'

const user = {
  state: {
    hasLoadUser: false,
    // token:'',
    userInfo: {},
    username:'',
    avatar: '',
    roles: [],
    permissions: [],
    routes: [],
    resourceUrl: null
  },

  mutations: {
    // SET_TOKEN: (state, token) => {
    //   state.token = token
    // },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
      state.hasLoadUser = true
    },
    UPD_USERINFO: (state, userInfo) => {
      state.userInfo = Object.assign(state.userInfo, userInfo)
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_ROUTES: (state, routes) => {
      state.routes = constantRoutes.concat(routes)
    },
    SET_RESOURCEURL: (state, resourceUrl) => {
      state.resourceUrl = resourceUrl
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo.username.trim(), userInfo.loginPwd, userInfo.codeObject, userInfo.category).then(res => {
          setToken(res.data.token, res.data.exp)
          //commit('SET_TOKEN', res.data.token)
          commit('SET_USERNAME', res.data.username)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取首页用户信息
    GetIndexInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          setToken(getToken(), res.data.exp)
          const user = res.data.userInfo;
          //const avatar = !user.avatar ? require("@/assets/image/profile.jpg") : user.avatar;
          setUsername(user.username);
          commit('SET_USERINFO', user)
          commit('SET_USERNAME', user.username)
          commit('SET_AVATAR', user.avatar)
          commit('SET_ROLES', res.data.roles)
          commit('SET_PERMISSIONS', res.data.auths)
          commit('SET_RESOURCEURL', res.data.resourceUrl)
          // 生成路由
          const accessedRoutes = filterAsyncRouter(res.data.menus)
          accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }).catch(error => {
          reject(error)
        })
      })
    },

    UpdateUserInfo({ commit }, userInfo) {
      let {nickName, phone, email, sex} = userInfo;
      commit('UPD_USERINFO', {nickName, phone, email, sex})
    },

    UpdateAvatar({ commit }, avatarInfo) {
      commit('SET_AVATAR', avatarInfo)
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          //commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_AVATAR', '')
          commit('SET_USERNAME', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      }else if(route.component === 'SubDirMenu'){
        route.component = SubDirMenu
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export const loadView = (view) => { // 路由懒加载
  //return (resolve) =>  require([`@/views/${view}`], resolve)
  return ()=>import(`@/views/${view}`)
}


export default user
